package com.qf.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.netflix.discovery.converters.Auto;
import com.qf.consants.RabbitMQConstants;
import com.qf.entity.Email;
import com.qf.entity.User;
import com.qf.feign.api.CarService;
import com.qf.feign.api.IUserService;
import com.qf.resp.ResultEntity;
import com.qf.utils.JWTUitls;
import com.qf.utils.PasswordEncoding;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sso")
public class SSOController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;

    @Autowired
    private CarService carService;

    @RequestMapping("/validataUsername")
    public Map<String, Object> validataUsername(String param) {
        Map<String, Object> map = new HashMap<>();

        // 1.根据用户名查询对对象
        User user = userService.getUserByUsername(param);
        if (user != null) {
            map.put("status", "n");
            map.put("info", "该用户已经被注册");
        } else {
            map.put("status", "y");
            map.put("info", "用户名可以使用");
        }
        return map;

    }

    @RequestMapping("/sendValidaCode")
    public void sendValidaCode(String email) {

        // 生成验证码
        String code = RandomStringUtils.random(4, false, true);
        ;

        Email email1Obj = new Email();
        email1Obj.setTitle("2008商城新用户在注册");
        email1Obj.setToUser(email);
        email1Obj.setContent("验证码:" + code);

        // 把邮件对象写到MQ中
        rabbitTemplate.convertAndSend(RabbitMQConstants.EMAIL_EXCAHNGE, null, email1Obj);


        // 把验证码存到redis中
        // SSO_REGSITER_854569279@qq.com
        // USER_XXXXX_854569279@qq.com
        stringRedisTemplate.opsForValue().set(RabbitMQConstants.SSO_REGISTER_SEND_CODE_KEY + email, code, 30, TimeUnit.SECONDS);
    }

    @RequestMapping("/register")
    public ResultEntity register(User user, String code) {

        // 对比验证码
        // 根据用户的邮箱从reids中查询验证码
        String redisCode = stringRedisTemplate.opsForValue().get(RabbitMQConstants.SSO_REGISTER_SEND_CODE_KEY + user.getEmail());

        if (!code.equals(redisCode)) {
            return ResultEntity.error("验证码有误或者已经失效");
        }

        // 密码加密
        user.setPassword(PasswordEncoding.hashPw(user.getPassword()));


        // 入库
        return userService.addUser(user);
    }

    @RequestMapping("/loginUser")
    public ResultEntity loginUser(String username, String password, @CookieValue(name = RabbitMQConstants.CAR_ANNO_NAME, required = false) String annoId) {
        System.out.println("username = [" + username + "], password = [" + password + "]");

        // 1、根据用户名查询对象
        User user = userService.getUserByUsername(username);

        // 2.判断用户是否存在
        if (user == null) {
            return ResultEntity.error("用户名或密码错误");
        }

        // 3.对比密码
        boolean checkpw = PasswordEncoding.checkpw(password, user.getPassword());

        if (!checkpw) {
            return ResultEntity.error("用户名或密码错误");
        }

        // 4.登录成功生成token
        Map<String, String> map = new HashMap<>();
        map.put("username", user.getUsername());
        map.put("email", user.getEmail());
        map.put("id", user.getId().toString());
        String token = JWTUitls.createToken(map, 60 * 60 * 24 * 7);


        // 5.合并购物车
        if (!StringUtils.isEmpty(annoId)) {

            // 1.根据匿名用户Id从redis中查询购物车数据
             carService.mergeCar(annoId,user.getId());
            System.out.println("调用合并购车完成了。。。。");

        }


        // 5.把token返回给客户端
        return ResultEntity.success(token);
    }

    @RequestMapping("/getUserByUsername")
    public ResultEntity getUserByUsername(@RequestHeader(name = RabbitMQConstants.SSO_LGOIN_TOKEN_NAME, required = false) String token) {

        if (!StringUtils.isEmpty(token)) {

            // 校验token
            DecodedJWT decodedJWT = JWTUitls.checkToken(token);

            // 2.从token中获取用户的信息
            String username = JWTUitls.getWithClaim(decodedJWT, "username");
            String email = JWTUitls.getWithClaim(decodedJWT, "email");

            User user = new User();
            user.setUsername(username);
            user.setEmail(email);
            return ResultEntity.success(user);
        }
        return ResultEntity.error("token为空");
    }
}
